<!--
 * @Description: 接口管理
 * @Author: wning
 * @Date: 2022-12-01 15:50:11
 * @LastEditors: Andy
 * @LastEditTime: 2023-03-01 09:59:23
-->

<template>
  <div class="x-page-col">
    <div class="x-left" style="min-width: 300px">
      <div class="top">
        <el-dropdown style="margin-right: 15px" @command="handleCommand" v-hasPermi="['upms:rank:add']">
          <el-button type="primary" plain>
            {{ $t('organization.rank.add') }}<em class="el-icon-arrow-down el-icon--right"></em>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="a">{{ $t('organization.rank.addRoot') }}</el-dropdown-item>
            <el-dropdown-item command="b">{{ $t('organization.rank.addSub') }}</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
      <Tree
        v-loading="treeLoading"
        :element-loading-text="$t('common.loading')"
        element-loading-spinner="el-icon-loading"
        style="padding: 0 15px 15px"
        ref="orgTreeComponents"
        :defaultProps="defaultProps"
        @handleNodeClick="handleNodeClick"
        :options="rankTreeData"
      ></Tree>
      <!-- <Tree :defaultProps='defaultProps' @handleNodeClick='handleNodeClick'></Tree> -->
    </div>
    <div class="x-right">
      <div class="rightTop flex-column">
        <div class="h3" v-if="currentNode?.shortName">
          <span>{{ currentNode?.shortName ?? '' }}</span>
          <el-button round size="small" @click="add(currentNode, true)" style="margin-left: 8px" v-if="currentNode?.id">
            {{ $t('common.edit') }}
          </el-button>
          <el-button round size="small" @click="handleDeletePrm(currentNode)" style="margin-left: 8px">
            {{ $t('common.delete') }}
          </el-button>
        </div>
        <el-breadcrumb separator-class="el-icon-arrow-right" v-if="currentNode?.path" class="sub-title">
          <el-breadcrumb-item v-for="(ele, eleIndex) in currentNode.path" :key="eleIndex">{{ ele }}</el-breadcrumb-item>
        </el-breadcrumb>
        <h4 class="sub_title">
          <em class="iconfont icon-a-Property1zuzhipeizhi"></em>
          {{ $t('organization.rank.subRank') }}
        </h4>
        <!-- <em class="el-icon-edit-outline"> </em>
        {{ nodeTreeTitle }} -->
      </div>
      <!--数据面板-->
      <x-data>
        <!--数据面板按钮插糟-->
        <template #tool>
          <el-row type="flex" class="tools" justify="space-between">
            <el-col :span="12">
              <el-button
                v-hasPermi="['upms:rank:add']"
                v-if="currentNode?.shortName"
                round
                size="small"
                @click="add({ orgId: currentNode.orgId })"
              >
                {{ $t('organization.rank.addSub') }}
              </el-button>
              <el-button
                v-hasPermi="['upms:rank:exportExcel']"
                v-if="currentNode?.shortName"
                round
                size="small"
                @click="handleExportRank"
              >
                {{ $t('common.export') }}
              </el-button>
            </el-col>
            <el-col :span="12" class="tools-config">
              <x-column-config :columns="columns" @updateColumns="updateColumns" @on-refresh="loadData" />
            </el-col>
          </el-row>
        </template>
        <x-table ref="tableCom" :pagination="pagination" :data-source="tableData" :loading="loading" :row-key="'id'">
          <!-- <el-table-column type="selection" width="55" />
          <el-table-column :label="$t('common.serialNumber')" :width="55" fixed type="index" /> -->
          <el-table-column
            v-for="(item, index) in tableColumns"
            :key="index"
            :prop="item.prop"
            :fixed="item.fixed"
            :show-overflow-tooltip="true"
            :width="item.width || 100"
            :min-width="item.minWidth || '-'"
            :label="item.label"
            :sortable="'custom'"
          >
            <template slot-scope="scope">
              <el-switch
                v-if="item.prop === 'state'"
                :value="scope.row[item.prop]"
                active-color="#4474F6"
                inactive-color="#A5A9B2"
                @change="handleChangeState(scope.row[item.prop], scope.row.id)"
                :disabled="!checkBntPermi('upms:rank:state')"
                :active-value="1"
                :inactive-value="0"
              >
              </el-switch>
              <span v-else>{{ scope.row[item.prop] | emptyVal }}</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" :label="$t('common.opeartion')" width="160">
            <template slot-scope="scope">
              <more-table-actions
                :action-list="actions"
                :permis-list="permissionsActions"
                :row="scope.row"
                @onActionClick="handleActions"
              />
            </template>
          </el-table-column>
        </x-table>
      </x-data>
    </div>
    <rank-add
      ref="rankDialog"
      @handleSuccess="loadRankTree"
      :dict-options="dictOptions"
      :rank-tree-options="rankTreeData"
      :options="optionsTree"
    ></rank-add>
  </div>
</template>
<script lang="jsx">
  import { TableListMixin, QueryDictMixin, PermissionsMixin } from '@package/utils'
  import { mapState } from 'pinia'
  import { pinias } from '@/common/pinia'
  import Tree from '../components/Tree.vue'
  import { columns, actions } from '../config/rank.js'
  import RankAdd from '../components/rankAdd.vue'
  import {
    apiDeleteRankBathDelete,
    listUrl,
    apiPostRankTree,
    apiPutDisableRank,
    apiPutEnableRank,
    rankExportUrl
  } from '../api/rank.js'
  import { EnumApiCode } from '../../../../../../globalEnum.js'
  import { apiPostOrganizTree } from '../api'

  const { cachedView } = pinias
  export default {
    name: 'Rank',
    components: {
      Tree,
      RankAdd
    },
    mixins: [TableListMixin, QueryDictMixin, PermissionsMixin],
    data() {
      return {
        listUrl,
        columns,
        actions,
        rankExportUrl,
        treeLoading: true,
        searchParams: {
          apiName: '',
          apiUrl: '',
          perms: '',
          state: ''
        },
        tableData: [],
        defaultProps: {
          children: 'children',
          label: 'rankName'
        },
        currentNode: {},
        optionsTree: [],
        rankTreeData: [],
        dictKeys: ['system.state', 'upms_rank.rank_type'],
        disableMixinCreated: true,
        creatFlag: false
      }
    },
    computed: {
      ...mapState(cachedView, ['visitedViews']),
      otherParam() {
        return { parentId: this.currentNode?.id ?? '' }
      }
    },
    mounted() {
      this.creatFlag = true
      this.loadOrgeTree()
      this.loadRankTree()
      this.initDictConfig()
    },
    activated() {
      const temp = this.visitedViews.filter((v) => v.path === this.$route.path)
      if (this.disableMixinCreated && this.creatFlag && !temp) {
        this.loadOrgeTree()
        this.loadRankTree()
      }
    },
    methods: {
      loadRankTree() {
        this.treeLoading = true
        apiPostRankTree()
          .then(({ code, data }) => {
            this.treeLoading = false
            if (code === EnumApiCode.Success) {
              this.rankTreeData = data
              if (this.rankTreeData?.length) {
                this.currentNode = 'id' in this.currentNode ? this.currentNode : this.rankTreeData[0]
              } else {
                this.currentNode = {}
              }
              if (this.currentNode?.id) {
                this.$nextTick(() => {
                  this.$refs.orgTreeComponents.setCurrentNode(this.currentNode.id)
                  setTimeout(() => {
                    this.currentNode = this.$refs.orgTreeComponents.getCurrentNode()
                  })
                })
                this.handleSearch()
              }
            }
          })
          .catch(() => (this.treeLoading = false))
      },
      loadOrgeTree() {
        apiPostOrganizTree({}).then((res) => {
          if (res.code === EnumApiCode.Success) {
            this.optionsTree = res.data
          }
        })
      },
      async handleChangeState(state, id) {
        const { code, msg } = state === 1 ? await apiPutDisableRank(id) : await apiPutEnableRank(id)
        if (code === EnumApiCode.Success) {
          this.$message.success(this.$t('system.user.successTips'))
          this.handleSearch()
        } else {
          this.$message.error(msg)
        }
      },

      handleNodeClick(val) {
        this.currentNode.path = []
        this.currentNode = val
        if (val?.parentName) {
          this.currentNode.path = [val.parentName, this.currentNode.shortName]
        }
        this.handleSearch()
      },
      handleCommand(command) {
        if (command === 'a') {
          this.$refs.rankDialog.handleOpen({ parentId: 0 })
        } else if (command === 'b') {
          this.$refs.rankDialog.handleOpen({ parentId: this.currentNode.id, orgId: this.currentNode.orgId })
        }
      },
      handleActions({ key, data }) {
        switch (key) {
          case 'edit': // 修改
            this.$refs.rankDialog.handleOpen(data)
            break
          case 'delete':
            this.handleDeletePrm(data)
            break
          case 'info':
            this.$refs.rankDialog.handleOpen(data)
            break
          default:
            break
        }
      },
      handleDeletePrm(data) {
        this.$confirm(this.$t('organization.rank.deleteSure'), this.$t('organization.rank.tips'), {
          confirmButtonText: this.$t('common.sure'),
          cancelButtonText: this.$t('common.cancel')
        })
          .then(() => {
            this.handleDeleteRank(data.id)
          })
          .catch(() => {})
      },
      handleDeleteRank(id) {
        apiDeleteRankBathDelete(id).then((res) => {
          if (res.code === EnumApiCode.Success) {
            this.$message.success(this.$t('common.deleteSuccess'))
          } else {
            this.$message.error(res.msg)
          }
          this.loadRankTree()
        })
      },
      // 新增
      add(info = {}, isEdit = false) {
        const data = Object.assign(info, {
          parentId: isEdit ? this.currentNode.parentId : this.currentNode.id ?? '0'
        })
        this.$refs.rankDialog.handleOpen(data)
      },
      // 导出
      handleExportRank() {
        this.handleExport(this.rankExportUrl)
      },
      /**
       * 重置查询
       *
       */
      handleReset() {
        this.resetSearch()
      }
    }
  }
</script>
<style lang="scss" scoped>
  @import '../../../common/assets/style/variables';

  .x-right {
    color: #424242;
    background-color: #fff;
  }

  .rightTop {
    padding: 15px 0 0 15px;
  }

  .top {
    margin-bottom: 16px;
    padding: 12px 15px;
    border-bottom: 1px solid #e0e0e0;
  }

  h4,
  .h3 {
    font-size: 20px;
    font-weight: 500;
    margin: 0;
    // padding: 0 20px;

    span {
      line-height: 30px;
    }
  }

  h4 {
    padding: 19px 20px;

    .iconfont {
      font-size: 20px;
    }
  }

  .tools {
    line-height: 42px;
    padding: 0 15px;
    border-radius: 3px;
    background-color: #eceff4;
  }

  h3 {
    // padding-top: 20px;
  }

  .el-breadcrumb.sub-title {
    font-size: 14px;
    line-height: 36px;
    padding-left: 7px;
  }

  .x-data-view {
    margin-top: 0;
    padding-top: 0;
    border-width: 0;
  }

  .info-hearder {
    font-size: 16px;

    // line-height: 60px;

    // margin-bottom: 10px;
    padding: 15px;
    color: $x-item-text-color;

    // border-bottom: 1px solid #e0e0e0;

    .el-icon-edit-outline {
      font-size: 18px;
      vertical-align: middle;
    }
  }
  // .leftTree {
  //   width: 200px;
  // }
  // .rightContent {
  //   width: calc(100% - 200px);
  // }
  // .pageRank {
  //   box-sizing: border-box;
  //   display: flex;
  //   height: 100%;
  // }
</style>
